package com.viewplug.view.custom;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.*;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.viewplug.R;

/**
 * Created by mac_wk on 14-12-25.
 */
public class CustomGuaView extends View {


    private final static String TAG = "CustomGuaView";

    public CustomGuaView(Context context) {
        this(context, null);
    }

    public CustomGuaView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomGuaView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CustomGuaView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        this(context, attrs, defStyleAttr);
    }

    private Handler handler = null;
    //是否完成
    private volatile boolean isComplete = false;
    //记录用户绘制的Path
    private Path mPath = null;
    //绘制背景
    private Paint mBackGroundPaint = null;
    //绘制用户动作
    private Paint mUserPaint = null;
    private PointF pointF = new PointF();
    /**
     * 内存中创建的Canvas
     */
    private Canvas mCanvas;
    //用户绘制的文本
    private String text = "$0";
    //字体大小
    private int fontSize = 32;
    //字体颜色
    private int color = Color.DKGRAY;
    private Rect mTextBound = new Rect();
    private float textScacleX = 2f;
    //画布
    private Bitmap mBitmap;
    //画布上得图片
    private Bitmap pic;
    //设置所占百分比
    private int allowPercent = 70;
    //全部面积
    private int totalArea;
    private int backgroundColor = Color.parseColor("#c0c0c0");
    private MyThread myThread = null;
    private final static int CHECKED = 1;
    private PorterDuffXfermode porterDuffXfermode_clear;
    private PorterDuffXfermode porterDuffXfermode_dst_out;

    private void initViews() {
        myThread = new MyThread();
        //设置为守护线程
        myThread.setDaemon(true);
        myThread.start();
        mPath = new Path();
        //设置画背景的时候的画笔
        updateFontPaint();
        //设置用户滑动的画笔
        mUserPaint = new Paint();
        mUserPaint.setColor(Color.parseColor("#c0c0c0"));
        mUserPaint.setAntiAlias(true);
        mUserPaint.setDither(true);
        mUserPaint.setStyle(Paint.Style.STROKE);
        mUserPaint.setStrokeJoin(Paint.Join.ROUND); // 圆角
        mUserPaint.setStrokeCap(Paint.Cap.ROUND); // 圆角
        // 设置画笔宽度
        mUserPaint.setStrokeWidth(20);
        pic = BitmapFactory.decodeResource(getResources(),
                R.drawable.s_title);
        porterDuffXfermode_clear = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
        porterDuffXfermode_dst_out = new PorterDuffXfermode(PorterDuff.Mode.DST_OUT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        totalArea = width * height;
        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
        //设置画笔
        mUserPaint.setStyle(Paint.Style.FILL);
        mCanvas.drawColor(Color.parseColor("#c0c0c0"));
        mCanvas.drawBitmap(pic, null, new RectF(0, 0, width, height), null);
    }


    public void restart() {
        isComplete = false;
        Paint paint = new Paint();
        paint.setXfermode(porterDuffXfermode_clear);
        mCanvas.drawPaint(paint);
        paint.setXfermode(porterDuffXfermode_dst_out);
        mCanvas.drawColor(backgroundColor);
        mCanvas.drawBitmap(pic, null, new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight()), null);
        mPath.reset();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawText(getText(), (getWidth() / 2 - mTextBound.width() / 2),
                getHeight() / 2 + mTextBound.height() / 2, mBackGroundPaint);
        if (!isComplete) {
            drawPath();
            canvas.drawBitmap(mBitmap, 0, 0, null);
        } else {
            if (customGuaCompleteListener != null)
                customGuaCompleteListener.onFinish();
        }
    }

    private void drawPath() {
        mUserPaint.setStyle(Paint.Style.STROKE);
        mUserPaint
                .setXfermode(porterDuffXfermode_dst_out);
        mCanvas.drawPath(mPath, mUserPaint);
    }

    private void updateFontPaint() {
        mBackGroundPaint = new Paint();
        mBackGroundPaint.setStyle(Paint.Style.FILL);
        mBackGroundPaint.setTextScaleX(getTextScacleX());
        mBackGroundPaint.setColor(getColor());
        mBackGroundPaint.setTextSize(getFontSize());
        mBackGroundPaint.getTextBounds(getText().toString(), 0, getText().length(), mTextBound);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                pointF.set(event.getX(), event.getY());
                mPath.moveTo(pointF.x, pointF.y);
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float y = event.getY();
                if (Math.abs(x - pointF.x) > 2 || Math.abs(pointF.y - y) > 2)
                    mPath.lineTo(event.getX(), event.getY());
                pointF.set(x, y);
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                handler.sendEmptyMessage(CHECKED);
                break;
        }
        invalidate();
        return true;
    }

    public float getTextScacleX() {
        return textScacleX;
    }

    public void setTextScacleX(float textScacleX) {
        this.textScacleX = textScacleX;
        updateFontPaint();
        invalidate();
    }

    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
        updateFontPaint();
        invalidate();
    }

    public String getText() {
        if (text == null)
            text = "";
        return text;
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
        updateFontPaint();
        invalidate();
    }

    public void setText(String text) {
        if (text == null)
            text = "";
        this.text = text;
        updateFontPaint();
        invalidate();
    }

    public int getBackgroundColor() {
        return backgroundColor;
    }

    @Override
    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
        restart();
    }

    public Bitmap getBackGroundImg() {
        return pic;
    }
    public void setBackGroundImg(Bitmap pic) {
        this.pic.recycle();
        this.pic = pic;
        restart();
    }
    public void setBackgroudResource(int resId) {
        this.pic.recycle();
        this.pic = BitmapFactory.decodeResource(getResources(),
                resId);
        restart();
    }


    private class MyThread extends Thread {
        private void checked() {
            Bitmap bitmap = mBitmap;
            int[] mPixels = new int[(int) totalArea];
            int width = getWidth();
            int height = getHeight();
            int wipeArea = 0;
            //拿到所有得像素信息
            bitmap.getPixels(mPixels, 0, getWidth(), 0, 0, getWidth(), getHeight());
            //统计所有得擦除区域
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    int index = i + j * width;
                    if (mPixels[index] == 0) {
                        wipeArea++;
                    }
                }
            }
            //算出百分比
            if (wipeArea > 0 && totalArea > 0) {
                int percent = (wipeArea * 100 / totalArea);
                Log.d(TAG, percent + "%");
                if (percent >= allowPercent) {
                    isComplete = true;
                    postInvalidate();
                }
            }
        }

        @Override
        public void run() {
            super.run();
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            Looper.prepare();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case CHECKED:
                            checked();
                            break;
                    }
                }
            };
            Looper.loop();
        }
    }

    private CustomGuaCompleteListener customGuaCompleteListener;

    public void setCustomGuaCompleteListener(CustomGuaCompleteListener customGuaCompleteListener) {
        this.customGuaCompleteListener = customGuaCompleteListener;
    }

    public interface CustomGuaCompleteListener {
        public void onFinish();
    }

    public void destory() {
        handler.getLooper().quit();
        pic.recycle();
        pic = null;
        mBitmap.recycle();
        mBitmap = null;
    }
}
